package com.javatest.h2server;

import org.h2.tools.Server;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.sql.SQLException;
import java.util.concurrent.TimeUnit;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2018/8/16 9:38
 */
public class H2DBServerStartListener implements ServletContextListener {
    private static final Logger LOGGER = LoggerFactory.getLogger(H2DBServerStartListener.class);
    private static int Count = 5;
    //H2数据库服务器启动实例
    private Server server;

    /**
     * Web应用初始化时启动H2数据库
     *
     * @param servletContextEvent
     */
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        try {
            LOGGER.info("正在启动h2数据库...");
            //使用org.h2.tools.Server这个类创建一个H2数据库的服务并启动服务，由于没有指定任何参数，那么H2数据库启动时默认占用的端口就是8082
            server = Server.createTcpServer().start();
            for (int i = Count; i >= 0; i--) {
                System.out.println("数据库启动中：" + i);
                TimeUnit.SECONDS.sleep(1);
            }
            InitH2DB.init();
            LOGGER.info("h2数据库启动成功...");
        } catch (SQLException e) {
            LOGGER.error("启动h2数据库出错：", e);
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            LOGGER.error("启动h2数据库出错：", e);
            e.printStackTrace();
        }
    }

    /**
     * Web应用销毁时停止H2数据库
     *
     * @param servletContextEvent
     */
    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        if (this.server != null) {
            // 停止H2数据库
            this.server.stop();
            this.server = null;
        }
    }
}
